const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    positions: [{
      position: '二头',
      value: 0
    }, {
      position: '背阔',
      value: 0
    }, {
      position: '三头',
      value: 0
    }, {
      position: '下背',
      value: 0
    }, {
      position: '胸部',
      value: 0
    }, {
      position: '臀部',
      value: 0
    }, {
      position: '腹部',
      value: 0
    }, {
      position: '前腿',
      value: 0
    }, {
      position: '上背',
      value: 0
    }, {
      position: '后腿',
      value: 0
    }]
  },
  add:function(e){
    const position = e.currentTarget.dataset.position;
    const positions = this.data.positions;
    positions.forEach(function(item){
      if (item.position===position){
        item.value++;
      }
    });
    this.setData({
      positions
    });
  },
  minus: function (e) {
    const position = e.currentTarget.dataset.position;
    const positions = this.data.positions;
    positions.forEach(function (item) {
      if (item.position === position) {
        const value = item.value-1;
        item.value = value>0?value:0;
      }
    });
    this.setData({
      positions
    });
  },
  reset: function() {
    const positions = this.data.positions;
    positions.forEach(function(item) {
      item.value = 0;
    });
    this.setData({
      positions
    });
  },
  addAll: function() {
    const positions = this.data.positions;
    positions.forEach(function(item) {
      item.value = item.value + 1;
    });
    this.setData({
      positions
    });
  },
  minusAll: function() {
    const positions = this.data.positions;
    positions.forEach(function(item) {
      const value = item.value - 1;
      item.value = value>0?value:0;
    });
    this.setData({
      positions
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const trainId = wx.getStorageSync("trainId");
    const trainArchivesJson = wx.getStorageSync("trainArchives");
    const trainArchives = JSON.parse(trainArchivesJson);
    const positions = this.data.positions;
    positions.forEach(function(position) {
      trainArchives.forEach(function(archive) {
        if (position.position === archive.position) {
          position.value = archive.value;
        }
      });
    });
    this.setData({
      positions
    });
  },
  save: function() {
    const positions = this.data.positions;
    const trainId = wx.getStorageSync("trainId");
    const url = app.globalData.url;
    wx.request({
      url: url + '/train/saveTrainArchives',
      data: {
        trainId,
        trainArchives: positions
      },
      method: 'POST',
      success: function(response) {
        if (response.data.success) {
          wx.navigateBack({
            delta: 1
          });
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          })
        }
      }
    })
  }
})